package com.hqyj.crmdemo.config;

import com.hqyj.crmdemo.annotation.Auth;
import com.hqyj.crmdemo.entity.User;
import com.hqyj.crmdemo.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


@CrossOrigin
@Component
public class LoginIntercetor implements HandlerInterceptor {
    @Autowired
    JWTUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        handler instanceof HandlerHethod 是 true,表示访问的是Controller中的方法。
//        如果请求的不是Controller中的方法，那么就直接return true ,表示不拦截。|
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getParameter("token");
        //判断token是否有效
        Boolean aBoolean = jwtUtil.validToken(token);
        if (aBoolean) {
            //从token中获取对象
            User user = jwtUtil.getUser(token);
            request.setAttribute("user", user);

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(Auth.class)) {
                Auth annotation = method.getAnnotation(Auth.class);
                String role = annotation.role();//"1", "2" , "1,2"

                Integer rid = user.getrId();
                if (role.contains(rid.toString())) {
                    return true;
                } else {
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().println("{\"msg\":\"errrole\"}");
                    return false;
                }
            }
        }

        //无注解
        return true;
    }
}
